﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.Tools.INSVideoTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public string XUrl { get; set; }
        public string XUserName { get; set; }
        public string XPassword { get; set; }
        public int XCameraID { get; set; }
        public int XMode { get; set; }
        public string XLoginClientStrategy { get; set; }
        public string XLocalVideoFileName { get; set; }
        public string PartID { get; set; }

        protected System.Windows.Forms.Integration.WindowsFormsHost _winHost;

        public event Action<Window, string, IntPtr> LoadCompleted;
        
        public MainWindow(string xUrl, string xUserName, string xPassword, string xCameraID, string xLoginClientStrategy, string xLocalVideoFileName, string partID)
        {
            InitializeComponent();

            this.XUrl = xUrl;
            this.XUserName = xUserName;
            this.XPassword = xPassword;
            this.XCameraID = int.Parse(xCameraID);
            //if (!string.IsNullOrWhiteSpace(xMode))
            //{
            //    this.XMode = int.Parse(xMode);
            //}
            if (string.IsNullOrWhiteSpace(xLoginClientStrategy))
            {
                this.XLoginClientStrategy = "Always";
            }
            else
            {
                this.XLoginClientStrategy = xLoginClientStrategy;
            }
            this.XLocalVideoFileName = xLocalVideoFileName;
            this.PartID = partID;
        }

        private static VideoClient.ClientSummary videoclient;
        private static int LvcCount = 0;
        private static bool LoginSuccess = false;
        private static object s_lockObj = new object();

        private VideoClient.LiveViewControl _lvc;
        private MediaElement _mediaElement;
        private int _LastStatus = -1;
        private BackgroundWorker _backgroundWorker;

        public void ChangeCameraID(int _cameraId)
        {
            if (_lvc != null)
            {
                _lvc.LoadCamera(_cameraId, Guid.Empty);
                _lvc.StartVideo();
            }
        }

        private void Lvc_OnStatusChange(int Status)
        {
            if (_LastStatus != Status)
            {
                _LastStatus = Status;
                if (Status == 0 && !string.IsNullOrWhiteSpace(XLocalVideoFileName))
                {
                    _winHost.Visibility = Visibility.Collapsed;
                    _mediaElement.Visibility = Visibility.Visible;
                    _mediaElement.Source = new Uri(XLocalVideoFileName, UriKind.RelativeOrAbsolute);
                    _mediaElement.Play();
                }
            }
        }

        private void LoginClient_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            bool isVideoUseable = false;
            if ((bool)e.Result)
            {
                //加载
                bool isLoaded = _lvc.LoadCamera(XCameraID, Guid.Empty);
                if (isLoaded)
                {
                    int ret = _lvc.StartVideo();
                    if (ret != 0)
                    {
                        isVideoUseable = true;
                    }
                    else
                    {
                    }
                }
                else
                {
                }
            }

            if (!isVideoUseable && !string.IsNullOrWhiteSpace(XLocalVideoFileName))
            {
                _winHost.Visibility = Visibility.Collapsed;
                _mediaElement.Visibility = Visibility.Visible;
                try
                {
                    _mediaElement.Source = new Uri(XLocalVideoFileName, UriKind.RelativeOrAbsolute);
                    _mediaElement.Play();
                }
                catch (Exception ex)
                {
                }
            }
        }

        private void LoginClient_DoWork(object sender, DoWorkEventArgs e)
        {
            lock (s_lockObj)
            {
                try
                {
                    if (!LoginSuccess)
                    {
                        //设置登录策略
                        LoginClientStrategy loginClientStrategy;
                        if (!Enum.TryParse<LoginClientStrategy>(XLoginClientStrategy, out loginClientStrategy))
                        {
                            loginClientStrategy = LoginClientStrategy.Always;
                        }

                        //登录
                        int loginNo = LoginClientFactory.CreateLoginClient(loginClientStrategy).LoginClient(videoclient, XUserName, XPassword, XUrl);
                        if (loginNo == 1)
                        {
                            LoginSuccess = true;
                            (Application.Current as App).WriteLog("视频登陆成功");
                        }
                    }
                }
                catch (Exception ex)
                {
                    (Application.Current as App).WriteLog("视频登陆异常:" +ex.StackTrace);
                }
            }
            e.Result = LoginSuccess;
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            if (LoadCompleted != null)
            {
                LoadCompleted(this, this.PartID, new System.Windows.Interop.WindowInteropHelper(this).Handle);
            }

            if (videoclient == null)
            {
                videoclient = new VideoClient.ClientSummary();
            }

            if (_lvc == null)
            {
                try
                {
                    _winHost = new System.Windows.Forms.Integration.WindowsFormsHost();
                    _ctlLayout.Children.Add(_winHost);

                    _mediaElement = new MediaElement();
                    _mediaElement.Visibility = Visibility.Collapsed;
                    _mediaElement.LoadedBehavior = MediaState.Manual;
                    _mediaElement.Stretch = Stretch.Fill;
                    _mediaElement.MediaEnded += (s, e1) =>
                    {
                        _mediaElement.Position = TimeSpan.Zero;
                        _mediaElement.Play();
                    };

                    _ctlLayout.Children.Add(_mediaElement);

                    _lvc = new VideoClient.LiveViewControl();
                    _winHost.Child = _lvc;
                    _lvc.BackColor = System.Drawing.Color.Black;
                    _lvc.HideCameraLabel = true;
                    _lvc.HideCameraStatus = true;
                    _lvc.Mute = true;
                    //_lvc.Size = new System.Drawing.Size(Convert.ToInt32(XWidth), Convert.ToInt32(XHeight));
                    _lvc.Tag = XCameraID;
                    _lvc.OnStatusChange += Lvc_OnStatusChange;
                }
                catch (Exception ex)
                {
                }
            }

            LvcCount++;
            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += LoginClient_DoWork;
            _backgroundWorker.RunWorkerCompleted += LoginClient_RunWorkerCompleted;
            _backgroundWorker.WorkerSupportsCancellation = true;
            _backgroundWorker.RunWorkerAsync();

        }

        private void Window_Closing_1(object sender, CancelEventArgs e)
        {
            try
            {
                if (_backgroundWorker != null && _backgroundWorker.IsBusy)
                {
                    _backgroundWorker.CancelAsync();
                    _backgroundWorker.DoWork -= LoginClient_DoWork;
                    _backgroundWorker.RunWorkerCompleted -= LoginClient_RunWorkerCompleted;
                    _backgroundWorker.Dispose();
                    _backgroundWorker = null;
                }

                //此处先清除winHost的引用，否则winHost dispose时不会被回收
                _ctlLayout.Children.Clear();
                if (_winHost != null)
                {
                    _winHost.Child = null;
                    _winHost.Dispose();
                    _winHost = null;
                }
                if (_mediaElement != null)
                {
                    _mediaElement.Close();
                    _mediaElement = null;
                }
                if (_lvc != null)
                {
                    string no = _lvc.Tag.ToString();
                    _lvc.OnStatusChange -= Lvc_OnStatusChange;
                    _lvc.StopVideo();
                    _lvc.ClearCamera();
                    _lvc.Dispose();
                    _lvc = null;

                    LvcCount--;
                    if (LvcCount <= 0)
                    {
                        LvcCount = 0;
                        if (videoclient != null)
                        {
                            videoclient.LogoutClient();
                            videoclient.Dispose();
                            videoclient = null;
                            LoginSuccess = false;
                            LoginClientFactory.ClearLoginClientInfo();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
}
